package com.qdlc.p2p.biz.service.impl;

import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qd.p2p.adapter.AdaptedRequestHandleService;
import com.qd.p2p.adapter.param.RechargeByPageParameter;
import com.qd.p2p.adapter.response.HtmlResponse;
import com.qdlc.p2p.biz.executer.AbstractExecuter;
import com.qdlc.p2p.biz.executer.ExecuterHelper;
import com.qdlc.p2p.biz.executer.impl.SystemRechargeSuccessExecuter;
import com.qdlc.p2p.biz.service.AccountRechargeService;
import com.qdlc.p2p.biz.util.NotifyRequestUrl;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.RechargeConstant;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.RandomUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter;
import com.qdlc.p2p.dal.dao.AccountRechargeDao;
import com.qdlc.p2p.dal.dto.AccountRecharge;
import com.qdlc.p2p.dal.dto.Operator;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.AccountRechargeModel;
import com.qdlc.p2p.dal.util.SystemConfigs;
import com.qdlc.p2p.dal.util.UserUtils;

@Service("accountRechargeService")
public class AccountRechargeServiceImpl implements AccountRechargeService {

    @Resource
    private AccountRechargeDao accountRechargeDao;
    
    @Resource
    AdaptedRequestHandleService adaptedRequestHandleService;
    
    /**
     * [网银充值] 充值
     * @param user
     * @param money
     * @return
     * @author linya
     */
    @Override
    public ReturnResult doRecharge(User user, double money){
    	
    	//充值接口请求
		RechargeByPageParameter parameter = new RechargeByPageParameter();
		parameter.setPlatformUserId(user.getTppUserCustId());
		parameter.setAmount(money);
		parameter.setOrderId(RandomUtil.getRandomNumString(8));
		parameter.setPageUrl(NotifyRequestUrl.RECHARGE_PAGE_NOTIFY_URL);
		parameter.setReturnUrl(NotifyRequestUrl.RECHARGE_RETURN_NOTIFY_URL);
		HtmlResponse rechargeHtmlResponse = adaptedRequestHandleService.rechargeByPage(parameter);
		if(rechargeHtmlResponse == null){
			return ReturnResult.SERVER_BUSY;
		}
    	if(!rechargeHtmlResponse.isSuccess()){
    		return new ReturnResult(rechargeHtmlResponse.getResponseMsg());
    	}
    	
    	//请求成功后，保存充值记录
    	AccountRecharge ar = new AccountRecharge(parameter.getOrderId(), user, money, RechargeConstant.PAY_ONLINE_TYPE, Constant.TPP_NAME);
		add(ar);
    	
		ReturnResult result = new ReturnResult();
		result.addExtra("html", rechargeHtmlResponse.getHtml());
    	return result;
    }
    
	/**
	 * [网银充值] 检测前置条件
	 * @param user
	 * @return
	 * @throws Exception
	 */
    @Override
	public ReturnResult rechargePreCondition(User user, double money){
		
		UserIdentify userIdentify = UserUtils.getUserIdentify(user);
		if (userIdentify.getRealNameStatus() != 1) {
			return new ReturnResult("您还未开通第三方账户,请先开户!");
		}
		if (userIdentify.getMobilePhoneStatus() != 1) {
			return new ReturnResult("请先通过手机认证!");
		}
		
		if(money < 100){
			return new ReturnResult("充值的金额不能小于100元!");
		}
		
		return ReturnResult.SUCCESS;
	}
    
    @Override
    public AccountRecharge add(AccountRecharge r) {
        return accountRechargeDao.save(r);
    }

    @Override
    public PageDataList<AccountRechargeModel> list(AccountRechargeModel model) {
        return accountRechargeDao.list(model);
    }

    @Override
    public PageDataList<AccountRechargeModel> list(long userId, AccountRechargeModel model) {
        return accountRechargeDao.list(userId, model);
    }

    @Override
    public AccountRechargeModel getRechargeSummary(long userId) {
        return accountRechargeDao.getRechargeSummary(userId);
    }

    @Override
    public int count(int status) {
        return accountRechargeDao.count(status);
    }

    @Override
    public AccountRecharge find(long id) {
        return accountRechargeDao.find(id);
    }

    @Override
    public int rechargedUserCount() {
        return accountRechargeDao.rechargedUserCount();
    }

    @Override
    public double rechargedAllMoney() {
        return accountRechargeDao.rechargedAllMoney();
    }

    @Override
    public double todayRechargedAllMoney() {
        return accountRechargeDao.todayRechargedAllMoney();
    }

    @Override
    public AccountRecharge getRechargeByOrder(String order) {
        return accountRechargeDao.getRechargeByTradeno(order);
    }

    @Override
    public void systemRecharge(String tradeNo, double amount, User toUser, Operator operator) {
        AccountRecharge recharge = new AccountRecharge(tradeNo, toUser, amount, RechargeConstant.PAY_SYSTEM_TYPE, RechargeConstant.PAY_SYSTEM_NAME);
        recharge.setRechargeFeeBear(RechargeConstant.FEE_BEAR_COMPANY);//平台垫付
        recharge.setStatus(AccountRechargeModel.RECHARGE_SUCCESS);
        recharge.setAmountIn(amount);
        accountRechargeDao.save(recharge);
        Global.setTransfer("recharge", recharge);
        AbstractExecuter executer = ExecuterHelper.getExecuter(SystemRechargeSuccessExecuter.class);
        executer.execute(amount, toUser, new User(SystemConfigs.ADMIN_ID));
    }

    @Override
    public void updateRechargeStatus(int interval, int status) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(DateUtil.getNow().getTime() - interval);
        QueryParam queryParam = QueryParam.getInstance();
        queryParam.addParam("status", 0);
        queryParam.addParam("addTime", SearchFilter.Operators.LTE, cal.getTime());
        List<AccountRecharge> list = accountRechargeDao.findByCriteria(queryParam);
        for (AccountRecharge ac : list) {
            accountRechargeDao.updateStatus(ac.getId(), status);
        }
    }

    @Override
    public double getRechargeAmountByDate(String date) {
        return accountRechargeDao.getRechargeAmountByDate(date);
    }

    @Override
    public double rechargedAllMomeny() {
        return accountRechargeDao.rechargedAllMomeny();
    }
}